package org.ysling.litemall.core.service;
// Copyright (c) [ysling] [927069313@qq.com]
// [litemall-plus] is licensed under Mulan PSL v2.
// You can use this software according to the terms and conditions of the Mulan PSL v2.
// You may obtain a copy of Mulan PSL v2 at:
//             http://license.coscl.org.cn/MulanPSL2
// THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
// EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
// MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
// See the Mulan PSL v2 for more details.
import org.springframework.beans.factory.annotation.Autowired;
import org.ysling.litemall.core.notify.NotifyService;
import org.ysling.litemall.core.utils.NotifyMessageUtil;
import org.ysling.litemall.core.weixin.service.SubscribeMessageService;
import org.ysling.litemall.db.constant.CouponUserConstant;
import org.ysling.litemall.db.constant.RewardConstant;
import org.ysling.litemall.db.domain.*;
import org.ysling.litemall.db.constant.GrouponConstant;
import org.ysling.litemall.db.constant.OrderConstant;
import org.springframework.stereotype.Service;
import org.ysling.litemall.db.service.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;

@Service
public class OrderCoreService {

    @Autowired
    private LitemallOrderService orderService;
    @Autowired
    private LitemallUserService userService;
    @Autowired
    private LitemallCouponUserService couponUserService;
    @Autowired
    private LitemallGoodsProductService goodsProductService;
    @Autowired
    private QCodeService qCodeService;
    @Autowired
    private LitemallGrouponRulesService grouponRulesService;
    @Autowired
    private LitemallGrouponService grouponService;
    @Autowired
    private LitemallOrderGoodsService orderGoodsService;
    @Autowired
    private LitemallRewardService rewardService;
    @Autowired
    private NotifyCoreService notifyCoreService;

    /**
     * 修改团购状态和订单状态
     * @param groupon
     */
    public synchronized void updateGrouponStatus(LitemallGroupon groupon){
        //获取团购规则信息
        LitemallGrouponRules grouponRules = grouponRulesService.findById(groupon.getRulesId());
        //仅当发起者才创建分享图片
        if (groupon.getGrouponId() == 0) {
            String goodsName = grouponRules.getGoodsName();
            String picUrl = grouponRules.getPicUrl();
            String url = qCodeService.createGrouponShareImage(goodsName, picUrl, groupon);
            groupon.setShareUrl(url);
        }

        //获取团购参与信息
        List<LitemallGroupon> grouponList = grouponService.queryJoinRecord(groupon.getGrouponId());
        if (groupon.getGrouponId() != 0 && (grouponList.size() >= grouponRules.getDiscountMember() - 1)) {
            //修改当前用户的团购信息
            LitemallGroupon grouponSource = grouponService.queryById(groupon.getGrouponId());
            this.updateStatus(grouponSource);
            //修改前面已经参与者团购状态
            for (LitemallGroupon grouponActivity : grouponList) {
                this.updateStatus(grouponActivity);
            }
        }else {
            //修改团购状态
            groupon.setStatus(GrouponConstant.STATUS_ON);
            if ( grouponService.updateVersionSelective(groupon) == 0) {
                throw new RuntimeException("更新团购信息失败");
            }

            //修改订单团购状态
            LitemallOrder order = orderService.findById(groupon.getOrderId());
            order.setOrderStatus(OrderConstant.STATUS_GROUPON_ON);
            if (orderService.updateSelective(order) == 0) {
                throw new RuntimeException("更新团购订单信息失败");
            }
        }
    }

    /**
     * 修改团购和订单状态，并发送通知邮件
     * @param grouponActivity
     */
    private void updateStatus(LitemallGroupon grouponActivity){
        grouponActivity.setStatus(GrouponConstant.STATUS_SUCCEED);
        if (grouponService.updateVersionSelective(grouponActivity) == 0) {
            throw new RuntimeException("更新团购信息失败");
        }

        //修改订单团购状态
        LitemallOrder order = orderService.findById(grouponActivity.getOrderId());
        order.setOrderStatus(OrderConstant.STATUS_GROUPON_SUCCEED);
        if (orderService.updateSelective(order) == 0) {
            throw new RuntimeException("更新团购订单信息失败");
        }

        //给商家发送通知
        notifyCoreService.orderNotify(order);
    }


    /**
     * 返还订单 如货品数量增加，优惠券返还，积分返还
     * @param order 订单
     */
    public void orderRelease(LitemallOrder order) {
        // 商品货品数量增加
        List<LitemallOrderGoods> orderGoodsList = orderGoodsService.queryByOid(order.getId());
        for (LitemallOrderGoods orderGoods : orderGoodsList) {
            Integer productId = orderGoods.getProductId();
            Short number = orderGoods.getNumber();
            if (goodsProductService.addStock(productId, number) == 0) {
                throw new RuntimeException("商品货品库存增加失败");
            }
        }

        //设置赏金取消
        LitemallReward reward = rewardService.findByOrderId(order.getId());
        if (reward != null){
            reward.setStatus(RewardConstant.STATUS_CANCEL);
            if (rewardService.updateVersionSelective(reward) <= 0){
                throw new RuntimeException("网络繁忙，请刷新重试");
            }
        }

        //设置团购取消状态
        LitemallGroupon groupon = grouponService.queryByOrderId(order.getId());
        if(groupon != null){
            LitemallGrouponRules grouponRules = grouponRulesService.findById(groupon.getRulesId());
            if (!grouponRules.getStatus().equals(GrouponConstant.RULE_STATUS_ON)){
                if(order.getActualPrice().compareTo(BigDecimal.ZERO) <= 0){
                    //团购未付款或订单金额为零，设置团购取消
                    groupon.setStatus(GrouponConstant.STATUS_CANCEL);
                    if (grouponService.updateVersionSelective(groupon) == 0) {
                        throw new RuntimeException("网络繁忙，请刷新重试");
                    }
                } else if(groupon.getStatus().equals(GrouponConstant.STATUS_ON)){
                    // 如果团购进行中，团购设置团购失败等待退款状态
                    groupon.setStatus(GrouponConstant.STATUS_FAIL);
                    if (grouponService.updateVersionSelective(groupon) == 0) {
                        throw new RuntimeException("网络繁忙，请刷新重试");
                    }
                }
            }
        }

        //返还积分
        BigDecimal integralPrice = order.getIntegralPrice();
        if (integralPrice.compareTo(BigDecimal.ZERO) > 0 && !OrderConstant.isAutoCancelStatus(order)){
            LitemallUser user = userService.findById(order.getUserId());
            if (user == null) throw new RuntimeException("未找到用户");
            BigDecimal userIntegral = user.getIntegral();
            //添加订单积分
            userIntegral = userIntegral.add(integralPrice);
            user.setIntegral(userIntegral);
            if (userService.updateVersionSelective(user) == 0){
                throw new RuntimeException("积分返还失败");
            }
        }

        // 返还优惠券
        List<LitemallCouponUser> couponUsers = couponUserService.findByOid(order.getId());
        for (LitemallCouponUser couponUser: couponUsers) {
            // 优惠券状态设置为可使用
            couponUser.setStatus(CouponUserConstant.STATUS_USABLE);
            couponUser.setUpdateTime(LocalDateTime.now());
            if (couponUserService.updateVersionSelective(couponUser) == 0) {
                throw new RuntimeException("优惠券返还失败");
            }
        }
    }
}
